package UDP.chat.improve;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

//信息发送类
public class thread_send extends Thread {

    private DatagramSocket Socket = null;//套接字
    private DatagramPacket Packet = null;//包
    private String name = null;//用户姓名
    private InetAddress ip;//发送到的IP
    private int port;//端口

    private static Boolean bj = true;//用于模拟停止线程

    /**
     * 构造方法
     */
    public thread_send() {
    }

    public thread_send(String name) {
        this.name = name;
    }

    public thread_send(String name, InetAddress ip, int port) {
        this.name = name;
        this.ip = ip;
        this.port = port;
    }

    @Override
    public void run() {
        try {
            Socket = new DatagramSocket();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));//获取命令行输入的内容
            while (bj) {
                //1.获取数据
                String ml = buffer.readLine();
                String sj = name+":"+ml;
                //2.准备数据包
                Packet = new DatagramPacket(sj.getBytes(), 0, sj.getBytes().length, ip, port);
                //3.发送数据
                Socket.send(Packet);

                //4.判断线程停止标注位
                if (ml.equals("bye")){
                    bj = false;
                    String zj = name+":下线了";
                    //2.准备数据包
                    Packet = new DatagramPacket(zj.getBytes(), 0,zj.getBytes().length, ip, port);
                    //3.发送数据
                    Socket.send(Packet);
                    //提示用户下线了
                    System.out.println("发送消息进程关闭");
                    //关闭资源
                    Socket.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
    }
}

